﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Transaction.recAcceptancehandlerNEW" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Text;

using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Transaction
{
    public class recAcceptancehandlerNEW : SIPO.Web.BaseHandler
    {
        private recAcceptanceRepo recAcceptanceDal = new recAcceptanceRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recAcceptanceDetailRepo recAccepDetail = new recAcceptanceDetailRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("review"): // Approve!
                    context.Response.Write(Review(context));
                    break;
                case ("open"):
                    context.Response.Write(UnReview(context));
                    break;
                default:
                    // do nothing
                    break;
            }
        }

        public string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
                string jsonString = string.Empty;
                jsonString = context.Server.UrlDecode(sr.ReadToEnd());

                Newtonsoft.Json.JsonSerializerSettings set = new Newtonsoft.Json.JsonSerializerSettings();
                set.Culture  = System.Globalization.CultureInfo.GetCultureInfo("id-ID");
                var objAcceptance = Newtonsoft.Json.JsonConvert.DeserializeObject<recAcceptance>(jsonString, set);
                sr.Close();
                sr.Dispose();
                 
                objAcceptance.EntryDate = DateTime.Now;
                objAcceptance.CreatedDate = DateTime.Now;
                objAcceptance.CreatedBy = base.UserLoggedIn;

                decimal sumValues = 0m;
                objAcceptance.Details.ForEach(delegate(recAcceptanceDetail dtl)
                {
                    if (dtl.Level == 1)
                    {
                        dtl.SectorCode = int.Parse(dtl.ID);
                        sumValues = dtl.Values.Value + sumValues;
                    }
                    else if (dtl.Level == 2)
                    {
                        var codes = dtl.ID.Split('.');
                        if (codes.Length > 1)
                        {
                            dtl.SectorCode = int.Parse(codes[0]);
                            dtl.SubSectorCode = int.Parse(codes[1]);
                        }
                    }
                    else if (dtl.Level == 3)
                    {
                        var codes = dtl.ID.Split('.');
                        if (codes.Length > 1)
                        {
                            dtl.SectorCode = int.Parse(codes[0]);
                            dtl.SubSectorCode = int.Parse(codes[1]);
                            dtl.SubSubSectorCode = int.Parse(codes[2]);
                        }
                    }

                    dtl.CreatedDate = DateTime.Now;
                    dtl.CreatedBy = base.UserLoggedIn;

                });

                objAcceptance.sumValues = sumValues;
                
                recAcceptanceDal.Save(objAcceptance, objAcceptance.Details);

                helper.Message = "Data berhasil di simpan!";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recAcceptancehanlder.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        public string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recAcceptance.Fields.AcceptanceId : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recAcceptance> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recAcceptanceDal.SelectScalar(SQL.Function.Aggregate.Count, recAcceptance.Fields.AcceptanceId));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recAcceptanceDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recAcceptancehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }
        public string Review(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();
            int id = int.Parse(context.Request.Params["acceptanceid"]);
            try
            {
                recAcceptance objAcceptance = new recAcceptance();
                objAcceptance.AcceptanceId = id;
                objAcceptance.ReviewDate = DateTime.Now;
                objAcceptance.UpdatedDate = DateTime.Now;
                objAcceptance.UpdatedBy = base.UserLoggedIn;
                
                recAcceptanceDal.Review(objAcceptance);
                helper.Message = "Data berhasil di setujui !";
                helper.IsSuccess = true;

            }
            catch (Exception ex)
            {
                helper.Message = ex.Message;
                helper.IsSuccess = false;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Review";
                log.LogMessage = helper.Message;
                log.LogSource = "recAcceptancehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }
        public string UnReview(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();
            int id = int.Parse(context.Request.Params["acceptanceid"]);
            try
            {
                recAcceptance objAcceptance = new recAcceptance();
                objAcceptance.AcceptanceId = id;
                objAcceptance.ReviewDate = null;
                objAcceptance.UpdatedDate = DateTime.Now;
                objAcceptance.UpdatedBy = base.UserLoggedIn;
                
                recAcceptanceDal.UnReview(objAcceptance);
                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;

            }
            catch (Exception ex)
            {
                helper.Message = ex.Message;
                helper.IsSuccess = false;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Review";
                log.LogMessage = helper.Message;
                log.LogSource = "recAcceptancehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }
    }
}